<?php

namespace app\api\model\plus\bargain;

use app\api\model\plus\bargain\Product as BargainProductModel;
use app\api\model\plus\bargain\ProductSku as BargainSkuModel;
use app\api\model\plus\bargain\Active as ActiveModel;
use app\api\model\settings\Setting as SettingModel;
use app\common\exception\BaseException;
use app\common\model\plus\bargain\Task as TaskModel;
use app\api\model\plus\bargain\TaskHelp as TaskHelpModel;
use app\api\service\bargain\Amount as AmountService;
use app\common\library\helper;

/**
 * 助力任务模型
 */
class Task extends TaskModel
{
    /**
     * 隐藏的字段
     * @var array
     */
    protected $hidden = [
        'peoples',
        'section',
        'is_delete',
        'app_id',
        'update_time',
    ];

    /**
     *我的助力列表
     * getList
     * @param $user_id
     * @param $params
     * \think\Paginator
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\DbException
     * @Author kevin
     * @date 2024/4/18 10:58
     */
    public function getList($user_id, $params)
    {

        $map = [];
        if($params['status'] !==''){
            $map[] = ['status','=',$params['status']];
        }
        $map[] = ['user_id','=',$user_id];
        $map[] = ['is_delete','=',0];
        // 助力活动列表
        return $this->where($map)->with(['file','active'])
            ->order(['create_time' => 'desc'])
            ->paginate($params);
    }

    /**
     *获取助力任务详情
     * getTaskDetail
     * @param $bargain_task_id
     * @param $user
     * array
     * @return array
     * @throws BaseException
     * @throws BaseException
     * @Author kevin
     * @date 2024/4/18 10:58
     */
    public function getTaskDetail($bargain_task_id, $user = false)
    {
        // 助力任务详情
        $task = static::detail($bargain_task_id, ['user']);
        if (empty($task)) {
            throw new BaseException(['msg' => '助力任务不存在']);
        }
        // 助力活动详情
        $active = ActiveModel::detail($task['bargain_activity_id'],'share_img_url');
        // 获取商品详情
        $product = BargainProductModel::detail($task['bargain_product_id'], ['product.image.file']);
        // 好友助力榜
        $help_list = TaskHelpModel::getListByTaskId($bargain_task_id);
//        foreach ($help_list as $key => $value){
//            $help_list[$key]['cut_money'] = '**';
//        }
        // 当前是否为发起人
        $is_creater = $this->isCreater($task, $user);
        // 当前是否已砍
        $is_cut = $this->isCut($help_list, $user);
        // 助力规则
        $setting = SettingModel::getBargain();
        $task["start_time"] = time();
        $task["start_time_text"] = date("Y-m-d H:i:s");

        $product_sku = BargainSkuModel::where('bargain_product_id',$task['bargain_product_id']) -> where('bargain_product_sku_id',$task['bargain_product_sku_id']) -> find();

        if($product_sku){
            $task['product_stock'] = $product_sku['bargain_stock'];
        }else{
            $task['product_stock'] = $product['stock'];
        }

        return compact('task', 'is_creater', 'is_cut', 'active', 'product', 'help_list', 'setting');
    }


    /**
     *新增助力任务
     * add
     * @param $user_id
     * @param $bargain_activity_id
     * @param $bargain_product_id
     * @param $bargain_product_sku_id
     * @param $product_sku_id
     * bool
     * @return bool
     * @Author kevin
     * @date 2024/4/18 10:58
     */
    public function add($user_id, $bargain_activity_id, $bargain_product_id, $bargain_product_sku_id, $product_sku_id)
    {
        // 获取活动详情
        $active = ActiveModel::detail($bargain_activity_id);
        // 获取商品详情
        $product = BargainProductModel::detail($bargain_product_id, ['product.image']);
        // 验证能否创建助力任务
        if (!$this->onVerify($active, $user_id, $product)) {
            return false;
        }
        // 商品sku信息
        $product_sku = BargainSkuModel::detail($bargain_product_sku_id, ['productSku']);
        // 创建助力任务
        return $this->addTask($user_id, $active, $product, $product_sku);
    }

    /**
     *创建助力任务记录
     * addTask
     * @param $user_id
     * @param $active
     * @param $product
     * @param $product_sku
     * bool
     * @return bool
     * @Author kevin
     * @date 2024/4/18 10:58
     */
    private function addTask($user_id, $active, $product, $product_sku)
    {
        // 分配助力金额区间
        $section = $this->calcBargainSection(
            $product_sku['product_price'],
            $product_sku['bargain_price'],
            $product_sku['bargain_num']
        );
        // 新增记录
        return $this->save([
            'bargain_activity_id' => $active['bargain_activity_id'],
            'user_id' => $user_id,
            'bargain_product_id' => $product['bargain_product_id'],
            'bargain_product_sku_id' => $product_sku['bargain_product_sku_id'],
            'product_price' => $product_sku['product_price'],
            'bargain_price' => $product_sku['bargain_price'],
            'actual_price' => $product_sku['product_price'],
            'peoples' => $product_sku['bargain_num'],
            'image_id' => $product['product']['image'][0]['image_id'],
            'product_name' => $product['product']['product_name'],
            'product_attr' => $product_sku['product_attr'],
            'product_sku_id' => $product_sku['product_sku_id'],
            'cut_people' => 0,
            'section' => $section,
            'cut_money' => 0.00,
            'end_time' => time() + ($active['together_time'] * 3600),
            'app_id' => self::$app_id,
        ]);

    }

    /**
     *帮砍一刀
     * helpCut
     * @param $user
     * false|mixed
     * @return false|mixed
     * @Author kevin
     * @date 2024/4/18 10:59
     */
    public function helpCut($user)
    {
        // 好友助力榜
        $helpList = TaskHelpModel::getListByTaskId($this['bargain_task_id']);


        // 当前是否已砍
        if ($this->isCut($helpList, $user)) {
            $this->error = '您已参与助力，请不要重复操作';
            return false;
        }
        // 帮砍一刀事件
        return $this->transaction(function () use ($user) {
            return $this->onCutEvent($user['user_id'], $this->isCreater($this, $user));
        });
    }

    /**
     *砍一刀的金额
     * getCutMoney
     * mixed
     * @return mixed
     * @Author kevin
     * @date 2024/4/18 11:00
     */
    public function getCutMoney()
    {
        return $this['section'][$this['cut_people']]??0;
    }

    /**
     *帮砍一刀事件
     * onCutEvent
     * @param $userId
     * @param $isCreater
     * true
     * @return true
     * @Author kevin
     * @date 2024/4/18 11:00
     */
    private function onCutEvent($userId, $isCreater = false)
    {
        // 助力金额
        $cutMoney = $this->getCutMoney();
        // 助力助力记录
        $model = new TaskHelpModel;
        $model->add($this, $userId, $cutMoney, $isCreater);
        // 实际购买金额
        $actualPrice = helper::bcsub($this['actual_price'], $cutMoney);
        // 更新助力任务信息
        $this->save([
            'cut_people' => ['inc', 1],
            'cut_money' => ['inc', $cutMoney],
            'actual_price' => $actualPrice,
            'is_floor' => helper::bcequal($actualPrice, $this['bargain_price']),
            'status' => helper::bcequal($actualPrice, $this['bargain_price']) == 0 ? 0 : 1,
        ]);
        return true;
    }


    /**
     *助力任务标记为已购买
     * setIsBuy
     * bool
     * @return bool
     * @Author kevin
     * @date 2024/4/18 11:00
     */
    public function setIsBuy()
    {
        return $this->save(['is_buy' => 1]);
    }

    /**
     *分配助力金额区间
     * calcBargainSection
     * @param $product_price
     * @param $bargain_price
     * @param $bargain_num
     * array|mixed
     * @return array|mixed
     * @throws \Exception
     * @throws \Exception
     * @Author kevin
     * @date 2024/4/18 11:00
     */
    private function calcBargainSection($product_price, $bargain_price, $bargain_num)
    {
        $AmountService = new AmountService(helper::bcsub($product_price, $bargain_price), $bargain_num);
        return $AmountService->handle()['items'];
    }

    /**
     *当前是否为发起人
     * isCreater
     * @param $task
     * @param $user
     * bool
     * @return bool
     * @Author kevin
     * @date 2024/4/18 11:00
     */
    private function isCreater($task, $user)
    {
        if ($user === false) return false;
        return $user['user_id'] == $task['user_id'];
    }


    /**
     * 验证是否有资格助力
     * checkCut
     * @param $user
     * @param $bargain_activity_id
     * bool
     * @return bool
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @Author kevin
     * @date 2024/5/27 16:05
     */
    public function checkCut($user,$bargain_activity_id,$bargain_task_id){

        $bargain_task = $this -> where('bargain_task_id',$bargain_task_id) -> find();
//        if($bargain_task['status'] !=0 ){ //只有助力中的订单才可以助力 根据需要不做限制
//            return false;
//        }

        if($bargain_task['is_buy'] !=0 ){ //只要未付款的情况下都可以助力
            return false;
        }


        $user_id = $bargain_task['user_id'];
        if($user['user_id'] == $user_id){ //用户不能砍自己发起的订单
            return false;
        }
        if((new TaskHelpModel()) -> where('user_id',$user['user_id']) -> count()){ //每位新用户仅有一次助力助力机会;
            return false;
        }

        $bargain_activity = (new ActiveModel()) -> where('bargain_activity_id',$bargain_activity_id) -> find();
        $user_reg_time = strtotime($user['create_time']); //用户注册时间
        if($bargain_activity['is_new_user'] == 1){ //指定新用户
            $reg_time = $bargain_activity['reg_time'];
            if($user_reg_time + $reg_time * 3600 < time()){ //注册时间大于24小时
                return false;
            }

        }

        return true;
    }

    /**
     *当前是否已砍
     * isCut
     * @param $helpList
     * @param $user
     * bool
     * @return bool
     * @Author kevin
     * @date 2024/4/18 11:01
     */
    private function isCut($helpList, $user)
    {
        if ($user === false) return false;
        foreach ($helpList as $item) {
            if ($item['user_id'] == $user['user_id']) return true;
        }
        return false;
    }

    /**
     *验证能否创建助力任务
     * onVerify
     * @param $active
     * @param $userId
     * @param $product
     * bool
     * @return bool
     * @Author kevin
     * @date 2024/4/18 11:01
     */
    private function onVerify($active, $userId, $product)
    {
        // 活动是否开始
        if ($active['start_time'] > time()) {
            $this->error = '很抱歉，当前助力活动未开始';
            return false;
        }
        // 活动是否到期合法
        if ($active['end_time'] < time()) {
            $this->error = '很抱歉，当前助力活动已结束';
            return false;
        }
        // 是否超过限购
        if ($product['limit_num'] > 0) {
            if ($this->getUserTaskCount($userId, $product['bargain_product_id']) >= $product['limit_num']) {
                $this->error = '已超过限购数量';
                return false;
            }
        }

        if ($this->getUserVerifyCount($userId, $product['bargain_product_id']) > 0) {
            $this->error = '很抱歉，您有当前商品的助力任务未完成';
            return false;
        }
        return true;
    }

    private function getUserTaskCount($userId, $bargain_product_id)
    {
        return (new self())->where('user_id', '=', $userId)
            ->where('bargain_product_id', '=', $bargain_product_id)
            ->count();
    }


    /**
     * 验证当前商品是否处于待完成助力中
     * getUserVerifyCount
     * @param $userId
     * @param $bargain_product_id
     * false|void
     * @return false|void
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\DbException
     * @Author kevin
     * @date 2024/4/22 10:49
     */
    private function getUserVerifyCount($userId, $bargain_product_id)
    {
        $map = [];
        $map[] = ['user_id','=',$userId];
        $map[] = ['bargain_product_id','=',$bargain_product_id];
        $map[] = ['status','=',0];
        return (new self())->where($map)->count();

    }

}